rm(list=ls())
library(tidyverse)

citycouncil_elections <- read_rds(here::here("data","processed","elections","citycouncil_elections_2000_2016.rds"))

# Check there is only city council members
citycouncil_elections %>% 
  distinct(descricao_cargo) # OK

# Check candidates situation
citycouncil_elections %>% 
  distinct(desc_sit_cand_tot)

# Exclude cases in which candidate was irregular, died, etc
citycouncil_elections <- citycouncil_elections %>% 
  filter(!str_detect(desc_sit_cand_tot,"^RENUNCIA/FALECIMENTO/CASSACAO ANTES DA ELEICAO$"),
         !str_detect(desc_sit_cand_tot, "^REGISTRO NEGADO ANTES DA ELEICAO$"),
         !str_detect(desc_sit_cand_tot, "^INDEFERIDO COM RECURSO$"),
         !str_detect(desc_sit_cand_tot, "^REGISTRO NEGADO APOS A ELEICAO$"))

citycouncil_elections %>% 
  distinct(desc_sit_cand_tot)

citycouncil_elections %>% 
  distinct(desc_sit_candidato)

# Clean other cases candidates declared irregular
citycouncil_elections <- citycouncil_elections %>% 
  filter((desc_sit_candidato %in% c("DEFERIDO","DEFERIDO COM RECURSO") | is.na(desc_sit_candidato)))

citycouncil_elections %>% 
  distinct(desc_sit_candidato)

citycouncil_elections %>% 
  distinct(desc_sit_cand_tot)

# Aggregate votes by party
citycouncil_party_shares <- citycouncil_elections %>% 
  group_by(codigo_municipio,
           nome_municipio,
           ano_eleicao,
           sigla_uf,
           sigla_partido,
           numero_partido) %>% 
  summarise(total_votos_partido = sum(total_votos)) %>% 
  group_by(codigo_municipio,
           ano_eleicao,
           sigla_uf) %>% 
  mutate(total_votos_mun = sum(total_votos_partido)) %>% 
  ungroup() %>% 
  mutate(vote_share_partido = total_votos_partido/total_votos_mun)

# Check if vote_shares sum to 100%

citycouncil_party_shares %>% 
  group_by(codigo_municipio,ano_eleicao,sigla_uf) %>% 
  summarise(sum_check = sum(vote_share_partido)) %>% 
  filter(!near(sum_check,1))

write_rds(citycouncil_party_shares,here::here("data","processed","elections","citycouncil_party_shares.rds"))
